var _Scene = require('component/scene.js');
var _layout = require('tools/layout.js');
var _relative = _layout.relative;
var _inherit = require('core/inherit.js');
var _global = require('game/global.js');
var R = require('game/texture.js').R;
var _PartialSprite = require('drawable/partialsprite.js');
var _Container = require('component/container.js');
var _textures = require('game/texture.js');
var _program = require('global/programs.js');

function partialSprite(id) {
    var frame = _textures.createFrame(id);
    return new _PartialSprite(_program.positionTexture.material(frame), frame);
}

function Progress(bg, fg) {
    _Container.call(this);
    this.addChild(this.mBg = _global.spriteNode(bg));
    this.addChild(this.mFg = partialSprite(fg));
    this.setSize(this.mBg.getSize());
    _relative.layoutTo(this.mFg, 0.5, 0.5, this.mBg, 0.5, 0.5);
}
_inherit(Progress, _Container);
Progress.prototype.setPercent = function (p) {
    var size = this.mFg.getSize();
    this.mFg.setRect(size[0] * p, size[1]);
};

/**
 * scale wrapper
 * @type {*}
 */
var Scene = _Scene.createScene(
    function (w, h) {
        this.addChild(this.mBg = _global.spriteNode(R.coverloading.bg));
        this.addChild(this.mProgress = new Progress(R.coverloading.p_bg, R.coverloading.p_fg));
        this.onSizeChange(w, h);
        this.startLoading();
    }
);
Scene.prototype.setGame = function (game) {
};
Scene.prototype.showCover = function () {
    this.mEvents.fire('finish', this);
};
Scene.prototype.update = function (context) {
    if (this.mFinish) {
        return;
    }
    this.mPercent += 0.2 * context.stride();
    if (this.mPercent >= 1) {
        this.mPercent = 1;
        this.mFinish = true;
        this.showCover();
    }
    this.mProgress.setPercent(this.mPercent);
};
Scene.prototype.startLoading = function () {
    this.mPercent = 0;
    this.mFinish = false;
};
Scene.prototype.onSizeChange = function (w, h) {
    this.setSize(w, h);
    var bgsize = this.mBg.getSize();
    this.mBg.setScale(w / bgsize[0], h / bgsize[1]);
    _relative.local.layoutTo(this.mProgress, 0.5, 0, this, 0.5, 0);
};

module.exports = Scene;